package cn.efunbox.afw.core.util;

import cn.efunbox.afw.core.entity.Cache;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;


/** 
 * @Description:
 * @author liwang
 * @date 2015年8月30日 下午3:12:48 
 *  
 */
public class CacheUtils {


	/**
     * 写个static方法块，里创建一个定时器
	 */
	static {

		new Timer().schedule(new TimerTask() {
			@Override
			public void run() {
				for (Iterator<Object> it = CacheUtils.pool.keySet().iterator(); it
						.hasNext();) {
					Object key = it.next();
					Cache value = CacheUtils.pool.get(key);
					if ((null != value) && (value.getActiveTime() + value.getTimeOut() < System.currentTimeMillis())) {
						CacheUtils.pool.remove(key);
						value = null;
					}
				}
			}
		}, new Date(), 3600000L);
	}

	/**
	 * 存储数据的map,至于为什么用ConcurrentHashMap，可以百度
	 */
	private static Map<Object, Cache> pool = new ConcurrentHashMap<Object, Cache>();

	/**
	 * 将数据加入到Map中
	 */
	public static void add(String key, Object value, int timeout) {
		Cache co = new Cache(key, value, timeout*1000L,System.currentTimeMillis());
		pool.put(key, co);
	}
	public static void add(String key, Object value, Date timeout) {
		Cache co = new Cache(key, value, timeout.getTime() ,0);
		pool.put(key, co);
	}
	/**
	 * 获取Map中的数据
	 */
	public static Object get(String key) {

		Cache value = pool.get(key);
		// value不等于空情况下，判断保存时间＋超时时间 是否小于当前时间，小于说明过期了。从map中移除掉
		if ((null != value) && (value.getActiveTime()+value.getTimeOut() < System.currentTimeMillis())) {
			pool.remove(key);
			value = null;
		}
		if (null == value) {
			return null;
		}
		return value;
	}

	public static void main(String[] args) throws Exception {
		CacheUtils.add("a", "A", 3); //保存3秒
		Date date= new Date(new Date().getTime()+2000);
		CacheUtils.add("b", "B", date); //保存3秒
		for (int i = 0; i < 100; i++) {
			Thread.sleep(500);
			System.out.println(CacheUtils.get("b"));
		}
	}
}